package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {

    private List<Map<String,String>> list = new ArrayList<>();
    private AjaxController(){
        Map<String,String> map= new HashMap<>();//这个map中存储一些帖子信息
        map.put("id","100");
        map.put("city","beijing");
        list.add(map);
        map= new HashMap<>();//这个map中存储一些帖子信息
        map.put("id","101");
        map.put("city","shanghai");
        list.add(map);

    }
    @PutMapping("/doAjaxPut")
    @ResponseBody
    public String doUpdateObject(@RequestParam Map<String,String> parammap){
        String id = parammap.get("id");
        Iterator<Map<String,String>> it = list.iterator();
        while (it.hasNext()){
            Map<String,String>map = it.next();
            if(map.get("id").equals(id)){
                map.put("city", parammap.get("city"));
            }
        }


        return "update ok";
    }
    @DeleteMapping("/doAjaxDelete/{id}")
    @ResponseBody
    public String doDeleteObject(@PathVariable String id){
//        for(Map<String,String> map:list){
//            if(map.get("id").equals(id)){
//                list.remove(map);//在迭代的同时事不允许直接这样删除的
//            }
//        }
        //基于迭代器执行删除操作
        Iterator<Map<String,String>> it = list.iterator();
        while (it.hasNext()){
            Map<String,String>map = it.next();
            if(map.get("id").equals(id)){
                it.remove();
            }
        }
        return "delete ok";
    }

    @PostMapping("/doAjaxPost")
    @ResponseBody
    //Map一般用来响应数据，但是如果要来接手数据的话就要添加@RequestParam或者@RequestBody注解
    //但是，@RequestParam描述的数据，请求头要用表单格式接受，@RequestBody描述的数据请求头要用json格式接收
    public String doSaveObject(@RequestParam Map<String,String> map){
        list.add(map);
        return "save ok";
    }

    @GetMapping(path={"/doAjaxGet/{city}","/doAjaxGet"})
    @ResponseBody
    public List<Map<String,String>> doAjaxGet(@PathVariable(required = false) String city){
       if(city==null||"".equals(city)){return list;}
        List<Map<String,String>> queryResult=new ArrayList<>();
       for(Map<String,String> map:list){
           if(map.get("city").contains(city)){
               queryResult.add(map);
           }
       }
        return  queryResult;
    }

    //通过ajax方法发送get请求。，访问此方法
    //方法的返回值要在页面上通过局部刷新的方式进行呈现
   @GetMapping("/doAjaxStart")
    public String doAjaxStart() throws InterruptedException {
       Thread.sleep(3000);
        return "Response Result Of Ajax Get Request 01 ";
    }

}
